﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;

namespace Chunker.Inpe.Downloader
{
    class InpeDownloader
    {
        const string URL = "http://satelite.cptec.inpe.br/acervo/goes_anteriores.jsp?data={0}%2F{1}%2F{2}";
        const string URL_REGEX = "http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";

        public static void Download(string folder, DateTime date)
        {
            string url = string.Format(URL, date.Year, date.Month, date.Day);
            string text = new WebClient().DownloadString(url);

            Regex regx = new Regex(URL_REGEX, RegexOptions.IgnoreCase);
            MatchCollection matches = regx.Matches(text);
            foreach (Match match in matches)
            {
                string address = match.Value;
                if (address.EndsWith("jpg") && !address.Contains("alta"))
                {
                    string filename = "goes12_" + address.Substring(address.LastIndexOf("web/") + 4).Replace('/', '_').Trim();
                    string filepath = Path.Combine(folder, filename);
                    Console.WriteLine("Downloading {0}...", filename);
                    if (File.Exists(filepath)) {
                        continue;
                    }

                    new WebClient().DownloadFile(address, filepath);
                }
            }
        }
    }
}
